package cn.com.connected.service.impl;

import cn.com.connected.base.cache.CacheService;
import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.base.exception.ErrorLogRobot;
import cn.com.connected.base.utils.StringTools;
import cn.com.connected.common.emnus.CacheKey;
import cn.com.connected.common.emnus.StatusType;
import cn.com.connected.common.utils.EmojiTools;
import cn.com.connected.service.TokenService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.stereotype.Service;
import cn.com.connected.service.MemberService;
import cn.com.connected.base.params.page.PageParam;
import cn.com.connected.base.params.page.BaseSearchDto;
import cn.com.connected.base.params.page.PageResult;
import cn.com.connected.base.utils.BeanCopyUtils;
import cn.com.connected.dto.MemberDto;
import cn.com.connected.dto.search.MemberSearchDto;
import cn.com.connected.entity.MemberEntity;
import cn.com.connected.mapper.MemberMapper;
import cn.com.connected.vo.MemberVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * 微信用户
 *
 * @author sms
 * @email sms@live.com
 * @date 2025-04-10 16:15:15
 */
@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberMapper, MemberEntity> implements MemberService {
    @Resource
    private MemberMapper memberMapper;

    @Resource
    private TokenService tokenService;

    @Resource
    private CacheService cacheService;

    public static MemberService memberService;

    @PostConstruct
    void init(){
        memberService = this;
    }


    @Override
    public MemberVo memberAdd(MemberDto memberDto) {
        MemberEntity entity = new MemberEntity();
        BeanCopyUtils.copy(memberDto,entity);
        memberMapper.insert(entity);

        return memberInfoById(entity.getId());
    }

    @Override
    public void memberEdit(String id, MemberDto memberDto) {
        MemberEntity entity = memberMapper.selectById(id);
        BeanCopyUtils.copy(memberDto,entity);
        entity.setId(id);
        memberMapper.updateById(entity);
    }


    @Override
    public void memberEditMobile(String id, String mobile) {
        if (StringUtils.isNotEmpty(mobile)){
            MemberEntity entity = memberMapper.selectById(id);
            entity.setMobile(mobile);
            memberMapper.updateById(entity);
        }
    }

    @Override
    public MemberVo memberInfoById(String id) {
        MemberEntity entity = memberMapper.selectById(id);

        MemberVo memberVo = BeanCopyUtils.copy(entity,new MemberVo());
        memberVo.setNickname(EmojiTools.resolveEmojiFromText(memberVo.getNickname()));
        return memberVo;
    }

    @Override
    @Klock(name = "openId",keys = {"#openId"})
    public String memberLogin(String openId) {
        LambdaQueryWrapper<MemberEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberEntity::getOpenid,openId);
        MemberEntity entity = this.getOne(wrapper);
        if (entity == null){
            entity = new MemberEntity();
            entity.setOpenid(openId);
            entity.setCreateTime(new Date());
            entity.setState(StatusType.t1.getValue());
            memberMapper.insert(entity);
            final String id = entity.getId();
            CompletableFuture.runAsync(()-> ErrorLogRobot.sendError2DingDing("新用户 id: "+id+" openId： "+openId));
        }

        String token = tokenService.createToken(entity.getId());
        cacheService.putObject(StringTools.format(CacheKey.LOGIN_TOKEN,entity.getId()),token);
        return token;
    }

    @Override
    public MemberVo memberInfoSet(String id, MemberDto memberDto) {
        memberDto.setNickname(EmojiTools.resolveEmoji2Text(memberDto.getNickname()));
        MemberEntity entity = memberMapper.selectById(id);

        BeanCopyUtils.copy(memberDto,entity);

        memberMapper.updateById(entity);
        return memberInfoById(id);
    }

    @Override
    public MemberVo memberInfoByMobile(String mobile) {
        LambdaQueryWrapper<MemberEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MemberEntity::getMobile,mobile);
        MemberEntity entity = memberMapper.selectOne(queryWrapper);
        return BeanCopyUtils.copy(entity,new MemberVo());
    }

    @Override
    public void memberDel(String id) {
        MemberEntity entity = memberMapper.selectById(id);
        entity.setState(StatusType.t0.getValue());
        memberMapper.updateById(entity);
    }

    @Override
    public PageResult<MemberVo> memberPage(BaseSearchDto<MemberSearchDto> searchParams) {
        LambdaQueryWrapper<MemberEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MemberEntity::getState,StatusType.t1.getValue());

        PageParam pageParam = searchParams.getPageParam();
        PageHelper.startPage(pageParam.getPageIndex(), pageParam.getPageSize());
        MemberSearchDto searchDto = searchParams.getSearchOption();

        wrapper.orderByDesc(Arrays.asList(MemberEntity::getCreateTime));

        Page<MemberEntity> page = (Page)memberMapper.selectList(wrapper);

        PageResult<MemberVo> pageResult = BeanCopyUtils.copyPageResult(page, MemberVo.class);

        return pageResult;
    }

}
